"""Result reporting and visualization."""

import json
from datetime import datetime
from typing import List
from dataclasses import asdict

from ..config import BenchmarkResult


class ResultReporter:
    """Generate reports from benchmark results."""
    
    @staticmethod
    def print_comparison_table(results: List[BenchmarkResult]):
        """
        Print comparison table of all results.
        
        Args:
            results: List of BenchmarkResult objects
        """
        print("\n" + "="*80)
        print("📊 Comprehensive Comparison Report")
        print("="*80)
        
        print(f"\n{'Backend':<10} {'Concur':<6} {'Throughput':<12} {'Tokens/s':<12} "
              f"{'Avg Latency':<12} {'P95 Latency':<12}")
        print("-" * 80)
        
        for result in results:
            print(f"{result.backend:<10} "
                  f"{result.concurrent_level:<6} "
                  f"{result.throughput:<12.2f} "
                  f"{result.tokens_per_second:<12.2f} "
                  f"{result.avg_latency:<12.2f} "
                  f"{result.p95_latency:<12.2f}")
    
    @staticmethod
    def save_to_json(results: List[BenchmarkResult], filename: str = None) -> str:
        """
        Save results to JSON file.
        
        Args:
            results: List of BenchmarkResult objects
            filename: Optional filename. Auto-generated if None.
            
        Returns:
            Path to saved file
        """
        if filename is None:
            timestamp = datetime.now().strftime("%Y%m%d_%H%M%S")
            filename = f"benchmark_results_{timestamp}.json"
        
        with open(filename, "w", encoding="utf-8") as f:
            json.dump([asdict(r) for r in results], f, indent=2, ensure_ascii=False)
        
        return filename
    
    @staticmethod
    def generate_summary(results: List[BenchmarkResult]) -> dict:
        """
        Generate summary statistics.
        
        Args:
            results: List of BenchmarkResult objects
            
        Returns:
            Dictionary with summary stats
        """
        if not results:
            return {}
        
        vllm_results = [r for r in results if r.backend == "vLLM"]
        ollama_results = [r for r in results if r.backend == "Ollama"]
        
        summary = {
            "total_tests": len(results),
            "vllm_tests": len(vllm_results),
            "ollama_tests": len(ollama_results),
        }
        
        if vllm_results:
            summary["vllm_avg_throughput"] = sum(r.throughput for r in vllm_results) / len(vllm_results)
            summary["vllm_avg_tokens_per_sec"] = sum(r.tokens_per_second for r in vllm_results) / len(vllm_results)
        
        if ollama_results:
            summary["ollama_avg_throughput"] = sum(r.throughput for r in ollama_results) / len(ollama_results)
            summary["ollama_avg_tokens_per_sec"] = sum(r.tokens_per_second for r in ollama_results) / len(ollama_results)
        
        return summary
    
    @staticmethod
    def print_full_report(results: List[BenchmarkResult]):
        """
        Print complete report with table and summary.
        
        Args:
            results: List of BenchmarkResult objects
        """
        ResultReporter.print_comparison_table(results)
        
        filename = ResultReporter.save_to_json(results)
        print(f"\n💾 Detailed results saved to: {filename}")
        
        summary = ResultReporter.generate_summary(results)
        if summary:
            print(f"\n📈 Summary:")
            print(f"   Total tests: {summary['total_tests']}")
            if "vllm_avg_throughput" in summary:
                print(f"   vLLM average throughput: {summary['vllm_avg_throughput']:.2f} req/s")
                print(f"   vLLM average token rate: {summary['vllm_avg_tokens_per_sec']:.2f} tokens/s")
            if "ollama_avg_throughput" in summary:
                print(f"   Ollama average throughput: {summary['ollama_avg_throughput']:.2f} req/s")
                print(f"   Ollama average token rate: {summary['ollama_avg_tokens_per_sec']:.2f} tokens/s")
        
        print("\n" + "="*80)
        print("✅ Test Complete!")
        print("="*80)

